<template>
  <div class="sub-header" > EDoc List</div>
  <ScrollArea :bot-margin="50">

    <table style="width: 100%;">
      <thead>
        <tr class="row list-header text-left">
          <th class="col-2">Short Description</th>
          <th class="col-2">Serial No</th>
          <th class="col-2">Task</th>
          <th class="col-3">File</th>
          <th class="col-2">Version</th>
          <th class="col-1">Complete</th>
        </tr>
      </thead>
      <hr />
      <tbody>
        <template v-for="(item, index) in state.data" :key="index">
          <div class="sub-header-2">
            {{ item && item.length ? item[0].description : '' }}
          </div>

          <tr
            v-for="(edoc, eIndex) in item"
            :key="eIndex"
            class="cursor-pointer row list-item"
            :class="getStatusColor(edoc.complete == 0 ? 'fail' : '')"
            style="text-align: left"
          >
            <td class="col-2 word-wrap">{{ edoc.short_description }}</td>
            <td class="col-2 word-wrap">{{ edoc.serial_no }}</td>
            <td class="col-2 word-wrap">{{ edoc.doc_name }}</td>
            <td class="col-3 word-wrap">
              <template v-if="edoc.file_url != ''">
                <div>
                  <q-icon name="attach_file" />
                  <a :href="djangoUrl + edoc.file_url" target="_blank">{{
                    filenameFromUrl(edoc.file_url)
                  }}</a>
                </div>
              </template>
            </td>
            <td class="col-2 word-wrap">
              <div>
                {{ edoc.version }}
              </div>
            </td>

            <td class="col-1 word-wrap">
              <q-checkbox
                @click="openComplete(edoc)"
                dense
                :disable="readOnly"
                :model-value="edoc.complete"
                :false-value="0"
                :true-value="1"
                label=""
                color="primary"
              />
            </td>
          </tr>
        </template>
      </tbody>
    </table>
  </ScrollArea>

  <q-dialog  v-model="completeDig">
    <MyDialog
      title="Confirm"
      content="Can not be changed after complete"
      :ok="updateComplete"
      :cancel="()=> completeDig =false"
    >
    </MyDialog>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue';
import { getStatusColor } from 'src/utils/getPublic';
import TabContainer from '../container/TabContainer.vue';
import {
  getRepairOrderEDocs,
  toggleEDocComplete,
} from 'src/services/repairOrderEdocService';
import { RepairOrderEDoc } from 'src/services/type';
import { resolveDjangoUrl } from 'src/boot/axios';
import { useQuasar } from 'quasar';
import MyDialog from '../container/MyDialog.vue';
import ScrollArea from 'src/components/ScrollArea.vue';

interface GroupRepairOrderEDoc {
  // grouped edoc by stock code
  [stock_code: string]: RepairOrderEDoc[];
}
export interface EDocTableProps {
  data: GroupRepairOrderEDoc;
}

const djangoUrl = resolveDjangoUrl();

const completeDig = ref(false);

const editedRow = ref();

const props = defineProps<{
  orderId: number;
  isReadOnly: boolean;
}>();

const $q = useQuasar();

const readOnly = ref(false);
if (props.isReadOnly) {
  readOnly.value = true;
}

const state = reactive<EDocTableProps>({
  data: {},
});

const emit = defineEmits(['update']);

async function initData() {
  const res = await getRepairOrderEDocs(props.orderId);
  console.log(res.data as RepairOrderEDoc[]);
  const ret = {} as GroupRepairOrderEDoc;
  res.data.filter(i=>i.parts!=null).map((v)=>{
      return {
        ...v,
        short_description:v.parts.description
      }
    })
    .forEach((item) => {
    if (!ret[item.stock_code]) {
      ret[item.stock_code] = [];
    }
    ret[item.stock_code].push(item);
  });  
  state.data = ret;
}

onMounted(() => {
  initData();
  emit('update');
});

function openComplete(edoc: RepairOrderEDoc) {
  editedRow.value = edoc;
  completeDig.value = true;
}

async function updateComplete() {

  if (readOnly.value) {
    return;
  }
  
  const res = await toggleEDocComplete(editedRow.value.id);
  const data = res.data as RepairOrderEDoc;
  editedRow.value.complete = data.complete;
  emit('update');
  completeDig.value = false
}

function save() {
  console.log('save');
}

function cancel() {
  console.log('cancel');
}

function filenameFromUrl(url: string) {
  const arr = url.split('/');
  return arr[arr.length - 1];
}
</script>
<style scoped>
table {
  border-collapse: collapse;
  table-layout: fixed;
}

td {
  padding: 0.8rem;
}

table thead {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: white;
}

</style>
